﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;


using DbSharp.Framework.DbObject;
using DbSharp.Framework.Common;

namespace DbSharp.Framework.CaseFile.Parser
{
    /// <summary>
    /// Parse ResultsetSection object  
    /// </summary>
    class ResultsetSectionParser
    {
        #region Private members
        private XElement m_ResultsetRootElement; 
        private ResultsetSection m_ResultsetSection = new ResultsetSection();
        private string m_CaseName;
        #endregion



        public ResultsetSectionParser(string caseName, XElement globalSettingElement, IEnumerable<IStatementDeclaration> listStatement, XElement resultsetRootElement)
        {
            m_CaseName = caseName;
            m_ResultsetRootElement = resultsetRootElement;
            DefaultRsOutputSettingParser defaultOutputSettingParser = new DefaultRsOutputSettingParser(globalSettingElement);
            DefaultRsOutputSetting defaultRsOutputSetting = defaultOutputSettingParser.Setting;

            var aliasAttribute = m_ResultsetRootElement.Attribute("statementAlias");
            string statementAlias = aliasAttribute.Value.Trim();
            IStatementDeclaration statementDeclaration = listStatement.FirstOrDefault(
                sql => StatementDeclarationExt.FindByAlias(sql, statementAlias));

            if (statementDeclaration == null)
            {
                string messageFmt = "statementAlias'{0}' used in Unit Case '{1}' cannot be found in sqlDeclarations and procDeclarations";
                string message = string.Format(messageFmt, statementAlias, m_CaseName);
                throw new DbSharpException(message);
            }

            //extract inputArguments for this ProcedureDeclaration
            XElement procInputArgsElement;
            procInputArgsElement = m_ResultsetRootElement.Element("inputArguments");
            var inputArgsProcessor = new StatementInputArgsProcessor(procInputArgsElement, statementDeclaration);
            var statementObj = inputArgsProcessor.StatementWithInArgValues;

            //Init ResultsetSection object
            var setting = ResultsetOutputSettingHelper.CreateResultsetOutputSetting(m_ResultsetRootElement, defaultRsOutputSetting);
            m_ResultsetSection.OutputSetting = setting;
            m_ResultsetSection.StatementDeclaration = statementObj;
            if (m_ResultsetRootElement.Name == "targetResultset")
                m_ResultsetSection.IsTargetResultset = true;
        }

         

        #region Public Properties/Methods

        public ResultsetSection ResultsetConfigSection
        {
            get { return m_ResultsetSection; }
        }

        #endregion

    }
}
